package com.tanhua.dubbo.server.api;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.PageUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.mongodb.client.result.DeleteResult;
import com.tanhua.dubbo.server.enums.IdType;
import com.tanhua.dubbo.server.pojo.FollowUser;
import com.tanhua.dubbo.server.pojo.Video;
import com.tanhua.dubbo.server.service.IdService;
import com.tanhua.dubbo.server.vo.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.ArrayList;
import java.util.List;

@Service(version = "1.0.0")
@Slf4j
public class VideoApiImpl implements VideoApi {

    @Autowired
    private IdService idService;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    private static final String VIDEO_FOLLOW_USER_KEY_PREFIX = "VIDEO_FOLLOW_USER_";

    /**
     * 发布小视频
     *
     * @param video 要发布的视频
     * @return 数据在表中的主键id
     */
    @Override
    public String saveVideo(Video video) {
        try {
            // 校验
            if (!ObjectUtil.isAllNotEmpty(video.getUserId(), video.getPicUrl(), video.getVideoUrl())) {
                return null;
            }

            // 设置id
            video.setId(ObjectId.get());
            video.setVid(idService.createId(IdType.VIDEO));

            // 发布时间
            video.setCreated(System.currentTimeMillis());

            // 保存到Mongodb中
            mongoTemplate.save(video);

            return video.getId().toHexString();
        } catch (Exception e) {
            log.error("视频发布失败~ video = " + video, e);
        }
        return null;
    }

    /**
     * 按照时间倒序分页查询推荐视频列表,优先展示推荐的视频,如果没有推荐的视频或已经查询完成,就需要查询系统视频数据
     *
     * @param userId   用户id
     * @param page     页码
     * @param pageSize 页大小
     * @return 包含推荐视频列表的PageInfo对象
     */
    @Override
    public PageInfo<Video> queryVideoList(Long userId, Integer page, Integer pageSize) {
        PageInfo<Video> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);

        String redisKey = "QUANZI_VIDEO_RECOMMEND_" + userId;
        String redisData = redisTemplate.opsForValue().get(redisKey);

        List<Long> finalVidList = new ArrayList<>();
        int recommendCount = 0;
        if (StrUtil.isNotEmpty(redisData)) {
            // 手动对查询数据进行分页
            List<String> vidList = StrUtil.split(redisData, ",");
            int[] startEnd = PageUtil.transToStartEnd(page - 1, pageSize);
            int startIndex = startEnd[0];
            int endIndex = Math.min(startEnd[1], vidList.size());

            for (int i = startIndex; i < endIndex; i++) {
                finalVidList.add(Convert.toLong(vidList.get(i)));
            }
            recommendCount = vidList.size();
        }
        if (CollectionUtil.isEmpty(finalVidList)) {
            // 计算前面的推荐数据到了第几页
            int totalPage = PageUtil.totalPage(recommendCount, pageSize);

            // 没有推荐或前面的推荐已经查询完毕
            // 需要去查询系统数据,即总表
            PageRequest pageRequest = PageRequest.of(page - totalPage - 1, pageSize, Sort.by(Sort.Order.desc("created")));
            Query query = new Query().with(pageRequest);
            List<Video> videoList = mongoTemplate.find(query, Video.class);
            pageInfo.setRecords(videoList);

            return pageInfo;
        }

        // 根据vid查询对应的视频数据
        Query query = Query.query(Criteria.where("vid").in(finalVidList));
        List<Video> videoList = mongoTemplate.find(query, Video.class);
        pageInfo.setRecords(videoList);

        return pageInfo;
    }

    @Override
    public Video queryVideoById(String publishId) {
        return mongoTemplate.findById(new ObjectId(publishId), Video.class);
    }

    /**
     * 关注用户
     *
     * @param userId       当前用户
     * @param followUserId 关注的目标用户
     * @return 关注成功:true,失败:false
     */
    @Override
    public Boolean followUser(Long userId, Long followUserId) {
        if (!ObjectUtil.isAllNotEmpty(userId, followUserId)) {
            return false;
        }
        try {
            // 需要将用户的关注列表放入Redis,方便后续查询
            // 使用Redis的hash结构
            if (isFollowUser(userId, followUserId)) {
                return false;
            }

            FollowUser followUser = new FollowUser();
            followUser.setId(ObjectId.get());
            followUser.setUserId(userId);
            followUser.setFollowUserId(followUserId);
            followUser.setCreated(System.currentTimeMillis());

            mongoTemplate.save(followUser);

            // 保存数据到Redis
            String redisKey = getVideoFollowUserKeyWithPrefix(userId);
            String hashKey = String.valueOf(followUserId);
            redisTemplate.opsForHash().put(redisKey, hashKey, "1");// 1只是一个标记,无所谓是多少

            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }

    /**
     * 取消关注用户
     *
     * @param userId       当前用户
     * @param followUserId 关注的目标用户
     * @return 取消关注成功:true,失败:false
     */
    @Override
    public Boolean disFollowUser(Long userId, Long followUserId) {
        if (!ObjectUtil.isAllNotEmpty(userId, followUserId)) {
            return false;
        }
        if (!isFollowUser(userId, followUserId)) {
            return false;
        }
        // 取消关注,即删除关注数据
        Query query = Query.query(Criteria.where("userId").is(userId)
                .and("followUserId").is(followUserId));
        DeleteResult result = mongoTemplate.remove(query, FollowUser.class);
        if (result.getDeletedCount() > 0) {
            // 删除Redis中的数据
            String redisKey = getVideoFollowUserKeyWithPrefix(userId);
            String hashKey = String.valueOf(followUserId);
            redisTemplate.opsForHash().delete(redisKey, hashKey);
            return true;
        }
        return false;
    }

    /**
     * 查询用户是否关注某个用户
     *
     * @param userId       当前用户
     * @param followUserId 关注的目标用户
     * @return 有关注:true,没有关注:false
     */
    @Override
    public Boolean isFollowUser(Long userId, Long followUserId) {
        String redisKey = getVideoFollowUserKeyWithPrefix(userId);
        String hashKey = String.valueOf(followUserId);
        return redisTemplate.opsForHash().hasKey(redisKey, hashKey);
    }

    private String getVideoFollowUserKeyWithPrefix(Long userId) {
        return VIDEO_FOLLOW_USER_KEY_PREFIX + userId;
    }
}